package com.usermanage.SecurityConfig;

import com.usermanage.Mapping.UserMapping;
import com.usermanage.Service.UserService;
import com.usermanage.beanParam.UserBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

/**
 * Created by 過客 on 2018/3/9
 */
@Slf4j
public class MyUserDetailService implements UserDetailsService {

    private final UserMapping userMapping;

    public MyUserDetailService(UserMapping u){
        this.userMapping = u;
    }
    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        UserBean bean = new UserBean();
        bean.setUser_email(email);
        Example<UserBean> example = Example.of(bean);
        Optional<UserBean> optional = userMapping.findOne(example);
        if (optional.isPresent()){
            UserBean userBean = optional.get();
            Set<GrantedAuthority> authorities = new HashSet<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_1"));
            boolean enabled = true;
            boolean accountNonExpired = true;
            boolean credentialsNonExpired = true;
            boolean accountNonLocked = true;
            UserDetail userdetails = new UserDetail(userBean.getId(), userBean.getUser_name(), userBean.getUser_password(),userBean.getUser_type(),authorities, accountNonExpired, accountNonLocked, credentialsNonExpired, enabled);
            return userdetails;
        }else{
            throw new RuntimeException("用户不存在！");
        }

    }
}
